﻿using UnityEditor.iOS.Xcode;
using System.IO;
using UnityEngine;

public static class DirectoryProcessor
{
    /// <summary>
    /// 拷贝文件
    /// </summary>
    /// <param name="source">原文件路径</param>
    /// <param name="targetPath">目标文件路径</param>
    public static void CopyFiles(string source , string targetPath)
    {
        
        if (File.Exists(source))
        {
            var exten = Path.GetExtension(source);
            if (exten == ExtensionName.META)
                return;
            File.Copy(source, targetPath, true);
        }
        else if (Directory.Exists(source))
        {
            DirectoryInfo sourceDir = new DirectoryInfo(source);
            var files = sourceDir.GetFiles();
            foreach (var item in files)
            {
                var exten = Path.GetExtension(source);
                if (exten == ExtensionName.META)
                    continue;
                var fileName = item.Name;
                var destPath = XCEditorUtils.CombinePaths(targetPath, fileName);
               // Debug.Log("CopyFile : " + item.FullName);
                File.Copy(item.FullName, destPath, true);
            }
            var directories = sourceDir.GetDirectories();
            foreach (var item in directories)
            {
                //Debug.Log("CopyDirectory : " + item.FullName);
                var dirName = item.Name;
                CopyFiles(XCEditorUtils.CombinePaths(source, dirName), XCEditorUtils.CombinePaths(targetPath, dirName));
            }
        }
    }

    /// <summary>
    /// 拷贝并增加到项目
    /// </summary>
    /// <param name="pbxProject">Xcode 工程</param>
    /// <param name="targetGuid">target  GUID</param>
    /// <param name="copyDirectoryPath">拷贝文件路径</param>
    /// <param name="buildPath">xcode的构建路径</param>
    /// <param name="currentDirectoryPath">基于构建路径的相对子路径 "" 就是根目录</param>
    /// <param name="needToAddBuild">是否需要添加到Build</param>
    public static void CopyAndAddBuildToXcode(PBXProject pbxProject, string targetGuid, string copyDirectoryPath, string buildPath, string currentDirectoryPath, bool needToAddBuild = true)
    {
        UnityEngine.Debug.Log("开始拷贝目标文件夹："+ copyDirectoryPath);
        //要拷贝的路径
        string unityDirectoryPath = copyDirectoryPath;
        //拷贝的目标路径
        string xcodeDirectoryPath = buildPath;

        if (!string.IsNullOrEmpty(currentDirectoryPath))
        {
           // unityDirectoryPath = XCEditorUtils.CombinePaths(unityDirectoryPath, currentDirectoryPath);
            xcodeDirectoryPath = XCEditorUtils.CombinePaths(xcodeDirectoryPath, currentDirectoryPath);
            Delete(xcodeDirectoryPath);
            Directory.CreateDirectory(xcodeDirectoryPath);
        }

        UnityEngine.Debug.Log("开始拷贝原文件夹：" + unityDirectoryPath);
        UnityEngine.Debug.Log("开始拷贝目标文件夹：" + copyDirectoryPath);

        var filse = Directory.GetFiles(unityDirectoryPath);
        foreach (string filePath in filse)
        {
            //过滤.meta文件
            string extension = Path.GetExtension(filePath);
            if (extension == ExtensionName.META)
                continue;
            //
            if (extension == ExtensionName.ARCHIVE)
            {
				var lib_ser_path = XCodeProjectConfig.LIBRARY_SEARCH_PATHS_KEY;
				var project_Path = XCodeProjectConfig.PROJECT_ROOT + currentDirectoryPath;
				UnityEngine.Debug.Log (string.Format("<color=2> Add New : {0} , Path :{1} </color>",lib_ser_path,project_Path));
                pbxProject.AddBuildProperty(targetGuid, XCodeProjectConfig.LIBRARY_SEARCH_PATHS_KEY, XCodeProjectConfig.PROJECT_ROOT + currentDirectoryPath);
            }

            string fileName = Path.GetFileName(filePath);
            string copyPath = Path.Combine(xcodeDirectoryPath, fileName);

            //有可能是.DS_Store文件，直接过滤
            if (fileName[0] == '.')
                continue;
            File.Delete(copyPath);
            File.Copy(filePath, copyPath);

            if (needToAddBuild)
            {
                string relativePath = Path.Combine(currentDirectoryPath, fileName);

                var fileGuidBuild = pbxProject.AddFile(relativePath, relativePath, PBXSourceTree.Source);
                pbxProject.AddFileToBuild(targetGuid, fileGuidBuild);
            }
        }

        var folders = Directory.GetDirectories(unityDirectoryPath);
        foreach (string directoryPath in folders)
        {
            string directoryName = Path.GetFileName(directoryPath);
            bool nextNeedToAddBuild = needToAddBuild;
            if (directoryName.Contains(ExtensionName.FRAMEWORK) || directoryName.Contains(ExtensionName.BUNDLE) || directoryName == XCodeProjectConfig.IMAGE_XCASSETS_DIRECTORY_NAME)
            {
                nextNeedToAddBuild = false;
            }
            CopyAndAddBuildToXcode(pbxProject, targetGuid, Path.Combine( copyDirectoryPath, directoryName), buildPath, Path.Combine(currentDirectoryPath, directoryName), nextNeedToAddBuild);
            if (directoryName.Contains(ExtensionName.FRAMEWORK) || directoryName.Contains(ExtensionName.BUNDLE))
            {
                string relativePath = Path.Combine(currentDirectoryPath, directoryName);
                pbxProject.AddFileToBuild(targetGuid, pbxProject.AddFile(relativePath, relativePath, PBXSourceTree.Source));
                pbxProject.AddBuildProperty(targetGuid, XCodeProjectConfig.FRAMEWORK_SEARCH_PATHS_KEY, XCodeProjectConfig.PROJECT_ROOT + currentDirectoryPath);
            }
        }
    }

    //拷贝文件夹或者文件
    public static void CopyAndReplace(string sourcePath, string copyPath)
    {
        Delete(copyPath);
        Directory.CreateDirectory(copyPath);
        foreach (var file in Directory.GetFiles(sourcePath))
        {
            if (Path.GetExtension(file) == ExtensionName.META)
                continue;
            File.Copy(file, Path.Combine(copyPath, Path.GetFileName(file)));
        }
        foreach (var dir in Directory.GetDirectories(sourcePath))
        {
            CopyAndReplace(dir, Path.Combine(copyPath, Path.GetFileName(dir)));
        }
    }

    //删除目标文件夹以及文件夹内的所有文件
    public static void Delete(string targetDirectoryPath)
    {
        if (!Directory.Exists(targetDirectoryPath))
            return;
        string[] filePaths = Directory.GetFiles(targetDirectoryPath);
        foreach (string filePath in filePaths)
        {
            File.SetAttributes(filePath, FileAttributes.Normal);
            File.Delete(filePath);
        }
        string[] directoryPaths = Directory.GetDirectories(targetDirectoryPath);
        foreach (string directoryPath in directoryPaths)
        {
            Delete(directoryPath);
        }
        Directory.Delete(targetDirectoryPath, false);
    }
}